﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Arch.Data;
using Microsoft.Practices.Unity;

namespace Arch.Samples.Mvc.Infrastructure
{
    public class ControllerBase : Controller
    {
        [Dependency]
        public IUnityContainer Container { get; set; }

        [Dependency]
        public IRepository Repository { get; set; }


        protected new void UpdateModel<TModel>(TModel model, string prefix = "", string[] includes = null,
                                            string[] excludes = null, IValueProvider valueProvider = null) where TModel : class
        {
            if(valueProvider == null)
                base.UpdateModel(model, prefix, includes, excludes);
            else
                base.UpdateModel(model, prefix, includes, excludes, valueProvider);
        }

        protected IEnumerable<SelectListItem> SelectList(IEnumerable items, string dataValueField = "Id", string dataTextField = "Name", object selectedValue = null,  string emptyValueField = null, string emptyTextField = "")
        {
            IEnumerable<SelectListItem> source = new SelectList(items, dataValueField, dataTextField, selectedValue);

            if (emptyValueField != null)
            {
                var list = new List<SelectListItem> { new SelectListItem { Text = emptyTextField, Value = emptyValueField } };
                list.AddRange(source);
                source = list;
            }
            return source;
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            try
            {
                if (filterContext.Exception != null)
                {
                    //Manage Action Exception
                }
                else
                {
                    try
                    {
                        Repository.SaveChanges();
                    }
                    catch (Exception)
                    {
                        //Manage Repository Exception
                        throw;
                    }
                }
            }
            catch(Exception)
            {
                //Manage General Exception
                throw;
            }
        }
    }
}